<?php

namespace App\Support\Services\SMSClient;

use App\Exceptions\ExceptionCode;
use App\Support\Helpers\HttpHelper;
use Illuminate\Support\Facades\Log;

class SMSClientService implements \App\Contracts\Services\SMSClient\SMSClientService
{
    public $conf;

    public function __construct($config)
    {
        $this->conf = $config;
    }

    /**
     * 短信发送
     * @param $mobile
     * @return string
     * $url = 'http://memberrest.sobeycloud.com:8080/memberapi/api/SMS/send';
     */
    public function sendMsg($mobile)
    {
        $url = $this->conf['host'].$this->conf['send_url'];
        $params = array(
            'mobile'=>$mobile,
            'tenantid'=>$this->conf['tenantid'],
            'type'=>4
        );
        ksort($params);
        $secret = $this->conf['secret'];
        $str = '';
        $timestamp = time();
        foreach ($params as $key=>$val) {
            $str .=$key.$val;
        }
        $sign = md5($timestamp.$str.$secret).';'.$timestamp;
        $data = HttpHelper::ihttp_request($url, $params, array('authorization'=>$sign,"content-type"=>"application/x-www-form-urlencoded;charset=UTF-8"));

        $return_data = json_decode($data['content'], true);
        Log::info($return_data);
        if ($return_data['code'] == 0) {
            return array('message'=>$return_data['description']);
        } else {
            return array('code'=>ExceptionCode::GENERAL,'message'=>$return_data['description']);
        }
    }

    /**
     * 手机验证
     * @param $mobile
     * @param $code
     * @return string
     * $url = 'http://memberrest.sobeycloud.com:8080/memberapi/api/user/mobileCheck';
     */
    public function checkMobileCode($mobile, $code)
    {
        $url = $this->conf['host'].$this->conf['check_url'];
        $params = array(
            'mobile'=>$mobile,
            'tenantid'=>$this->conf['tenantid'],
            'verify'=>$code
        );
        ksort($params);
        $secret = $this->conf['secret'];
        $str = '';
        $timestamp = time();
        foreach ($params as $key=>$val) {
            $str .=$key.$val;
        }
        $sign = md5($timestamp.$str.$secret).';'.$timestamp;
        $data = HttpHelper::ihttp_request($url, $params, array('authorization'=>$sign,"content-type"=>"application/x-www-form-urlencoded;charset=UTF-8"));

        $return_data = json_decode($data['content'], true);
        Log::info($return_data);
        if ($return_data['code'] == 0) {
            return array('code'=>0,'message'=>$return_data['description']);
        } else {
            return array('code'=>ExceptionCode::GENERAL,'message'=>$return_data['description']);
        }
    }
}
